#!/usr/bin/env python
# Usage: run_test <test>
# test: is the .sk file in src/tests to test
#
# Environment Variables:
# VERBOSE - show diff in baseline or error output
# UPDATE_BASELINE - update the baseline to the current output and pass the test

from __future__ import print_function

import argparse
import imp
import logging
import os
import shutil
import subprocess
import sys

common = imp.load_source(
    'common',
    os.path.join(os.path.dirname(sys.argv[0]), '../../runtime/tools/common.py'))

logger = logging.getLogger(__name__)


def runtest(args, test):
    cmd = [os.path.join(os.path.dirname(sys.argv[0]), '../../../build/bin/skip_serialization_generator'), test]
    result = subprocess.check_output(cmd)
    with common.tmpfile(
            prefix='tmp.run_test.',
            suffix='.sk') as fout:
        fout.write(result)
        fout.flush()
        backend_gen = "../../runtime/tools/skip_native_exec"
        cmd = [backend_gen, common.prelude(), test, fout.name, 'TestHelpers.sk']
        env = os.environ.copy()
        env['SKIP_DONT_REBUILD'] = '1'
        expectError = 'invalid/' in test
        result = common.RunCommand(test, cmd=cmd, env=env, expectError=expectError, expectedExtension='.exp')
        if not result.checkReturnCode():
            return False
        if result.report_diff():
            return False
        result.success()
        return True


def main():
    parser = argparse.ArgumentParser(
        description='Run skip_serialization_generator test',
        parents=[common.commonArguments(needsBackend=False)])
    parser.add_argument('test', help='is the .sk file in to test')
    args = common.parse_args(parser)

    if args.relative:
        os.chdir(args.relative)

    result = runtest(args, args.test)
    return 2 * (not result)


if __name__ == '__main__':
    rc = main()
    sys.exit(rc)
